"""
订单相关 Celery 任务
"""
from datetime import datetime, timedelta

try:
    from celery_app import celery_app
except Exception:
    # 兼容未启动celery时导入
    class _DummyCelery:
        def task(self, name=None, **kwargs):
            def _decorator(fn):
                return fn
            return _decorator
    celery_app = _DummyCelery()

from database import SessionLocal
from models.order_models import Order


@celery_app.task(name='tasks.orders.delete_unpaid_order')
def delete_unpaid_order(order_no: str):
    """
    精准删除：在订单创建时延迟10分钟触发
    只有当订单仍为未支付(status=0)时才执行删除
    """
    db = SessionLocal()
    try:
        od = db.query(Order).filter(Order.order_no == order_no).first()
        if not od:
            return {"deleted": False, "reason": "not_found"}
        if od.status != 0:
            return {"deleted": False, "reason": "not_unpaid"}
        # 防止时钟漂移，确保已超时
        if od.created_at > datetime.now() - timedelta(minutes=10):
            return {"deleted": False, "reason": "not_timeout"}
        db.delete(od)
        db.commit()
        return {"deleted": True}
    except Exception as e:
        db.rollback()
        return {"deleted": False, "error": str(e)}
    finally:
        db.close()


@celery_app.task(name='tasks.orders.cleanup_unpaid_orders')
def cleanup_unpaid_orders():
    """
    兜底清理：每分钟检查一遍所有超时未支付订单并删除
    """
    db = SessionLocal()
    try:
        deadline = datetime.now() - timedelta(minutes=10)
        overdue = db.query(Order).filter(Order.status == 0, Order.created_at < deadline).all()
        count = 0
        for od in overdue:
            db.delete(od)
            count += 1
        if count:
            db.commit()
        return {"deleted": count}
    except Exception as e:
        db.rollback()
        return {"deleted": 0, "error": str(e)}
    finally:
        db.close()














